package my.lang.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import script.service.JsonToServiceUtil;

/**
 * @author yanchangyou
 */
public abstract class FormatCodeAction extends MyAction {

    @Override
    public void actionPerformed(AnActionEvent e) {

        System.out.println("Hello, " + getId() + "! formatting...");
        final Editor editor = e.getData(CommonDataKeys.EDITOR);
        if (editor == null) {
            return;
        }
        final Document document = editor.getDocument();

        final String code = document.getText();

        WriteCommandAction.runWriteCommandAction(e.getProject(), () -> {
            String formattedCode = JsonToServiceUtil.format(code);
            document.setText(formattedCode.replace("\r", ""));
        });
    }

    public abstract String getId();

}